#include "mapwidget.h"
#include <QMessageBox>
#include <QMoveEvent>

void SButton::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        emit leftClicked();
    } else {
        emit rightClicked();
    }
}

MapWidget::MapWidget(QWidget *parent) : QWidget(parent)
{
    setBooms(30);
    setRows(20);
    setColumns(20);
    for (int i = 0; i < getRows(); i++) {
        for (int j = 0; j < getColumns(); j++) {
            SButton *button = new SButton;
            button->setParent(this);
            int d = 40;
            button->setGeometry(j * d, i * d, d, d);
            button->setCheckable(true);
            button->setFont(QFont("consolas", 20));
            connect(button, SIGNAL(leftClicked()), this, SLOT(clicked()));
            connect(button, SIGNAL(rightClicked()), this, SLOT(rightClicked()));
            buttons[i][j] = button;
        }
    }
    genMp();
    replay();
}

void MapWidget::clicked()
{
    int d = 40;
    QPushButton *button = qobject_cast<QPushButton *>(sender());
    int row = button->y() / d;
    int col = button->x() / d;

    open(row, col);

    updateMp();
    //  QMessageBox::information(this, QString::number(row) + " " + QString::number(col), "");
}

void MapWidget::rightClicked()
{
    int d = 40;
    QPushButton *button = qobject_cast<QPushButton *>(sender());
    int row = button->y() / d;
    int col = button->x() / d;
    //QMessageBox::information(this, "failure", "failure");
    turnFlag(row, col);
    updateMp();
}

void MapWidget::failure()
{
    openAll();
    updateMp();
    QMessageBox::information(this, "failure", "failure");
    genMp();
    replay();
    updateMp();
}

void MapWidget::win()
{
    QMessageBox::information(this, "win", "win");
    genMp();
    replay();
    updateMp();
}

void MapWidget::updateMp()
{
    for (int i = 0; i < getRows(); i++) {
        for (int j = 0; j < getColumns(); j++) {
            int state = getState(i, j);
            if (state == Closed) {
                buttons[i][j]->setChecked(false);
                buttons[i][j]->setText("");
            } else if (state == Opened) {
                if (isBoom(i, j) == true) {
                    buttons[i][j]->setText("X");
                } else {
                    buttons[i][j]->setChecked(true);
                    int val = getNum(i, j);
                    if (val != 0) {
                        buttons[i][j]->setText(QString::number(val));
                    }
                }
            } else {
                buttons[i][j]->setChecked(false);
                buttons[i][j]->setText("!");
            }
        }
    }
}
